<template>
  <ZContainer v-loading="loading"
              :noPadding="true"
              :noBorder="true"
              :class="[
                'bot-list',
                {
                  'bot-list--collapse':currentCollapse
                }
              ]">
    <div class="bot-list__wrapper flex h-full w-full relative">
      <div class="bot-list__wrapper-left overflow-hidden h-full flex flex-col"
           v-if="currentPermission['leftAuth']">
        <div style="padding: 0 16px"
             v-if="currentPermission['keywordAuth']">
          <el-input placeholder="Search"
                    prefix-icon="el-icon-search"
                    clearable
                    v-model="searchForm.name"
                    @input="keyWordsChange">
          </el-input>
        </div>

        <div class="flex-1 flex relative flex-col h-0"
             :style="{
          paddingTop:currentPermission['fastAuth'] ? 0: '16px'
        }">
          <BFastMenu @event:open-modal="openFastModal"
                     v-if="currentPermission['fastAuth']"
                     v-model="fastGuideTooltipVisible" />

          <div class="flex-1 flex overflow-auto h-0 flex-col">
            <BSort v-model="searchForm.order"
                   :fields="sortFields"
                   v-if="currentPermission['sortAuth']"
                   @event:change="refreshTable"
                   @event:back-default="backDefaultSort"
                   :collapse.sync="sortCollapse" />

            <BFilter v-model="searchForm.filter"
                     :collapse.sync="filterCollapse"
                     @event:change="refreshTable"
                     :omitKeys="['type']"
                     v-bind="currentFilterProps"
                     v-if="currentPermission['filterAuth']" />

            <BBlockStatus v-model="searchForm.blockStatus"
                          @event:change="refreshTable"
                          v-if="currentPermission['BlockStatusAuth']" />

            <BIntegrationGroup :options="integrations"
                               v-model="searchForm.integration"
                               @event:change="refreshTable"
                               v-if="currentPermission['integrationAuth']" />
          </div>

        </div>
      </div>

      <div class="bot-list__wrapper-right flex-1 w-0 flex flex-col">
        <BFast v-model="selectedFast"
               :collapse.sync="currentCollapse"
               v-bind="{
                  options:fasts,
                  disabled:fastLoading,
                  ...fastProps,
                  model:model
                }"
               @event:delete="onDeleteFast"
               @event:select="onSelectFast"
               @event:guide="openFastGuide"
               v-if="currentPermission['fastListAuth']" />

        <div class="bot-list__wrapper-right-action"
             v-if="$slots.toolbar && currentPermission['toolbarAuth']">
          <slot name="toolbar">
          </slot>
        </div>

        <div class="flex-1 flex flex-col relative h-0"
             v-loading="resourceLoading">
          <div class="bot-list__wrapper-right-list flex-1 overflow-auto relative h-0">
            <RecycleScroller class="h-full"
                             :items="resources"
                             :buffer="15"
                             :item-size="198"
                             size-field="height"
                             :key-field="this.rowKey"
                             v-if="resources && resources.length">
              <template v-slot="{item,active,index}">
                <div :class="['b-card flex flex-col cursor-pointer relative',
                              [`b-card-${model}`],
                              {
                                'b-card-selection--selected':model==='selection'&&isSelectedRow(item),
                                'b-card-selection--disabled':model==='selection'&&isDisabledRow(item) ,
                              }
                           ]"
                     :is-active="active"
                     @click.stop="onCommand(model==='selection'?'select':'draw',item,index)">
                  <div class="b-card-top flex flex-col justify-between">
                    <div class="b-card-top__top flex items-center">

                      <div class="b-card-top__top-line"
                           :style="{backgroundColor: useStatusColor(item.status)}"></div>

                      <div class="b-card-top__top__hover overflow-hidden relative flex items-center">
                        <div class="b-card-top__top__hover--status"
                             :style="{color:useStatusColor(item.status)}">{{item.status}}</div>
                      </div>

                      <div class="b-card-top__top-name w-4/6 ">
                        <ZTooltip :line="1"
                                  :content="item.name">
                          <span>{{item.name}}</span>
                        </ZTooltip>
                      </div>

                      <TagGroup :options="item.tagList || []"
                                class="flex-1" />

                      <el-tooltip :open-delay="1000"
                                  :content="item.isFavorite ? $t('removeFavorite') : $t('addFavorite')"
                                  effect="dark"
                                  v-if="currentPermission['collectAuth'] && item.businessType !== 'Template'"
                                  placement="top">
                        <img alt=""
                             @click.stop="onCommand('collect',item,index)"
                             class="b-card-top__top-favorites"
                             :src="item.isFavorite ? require('@/assets/favorites_active.png') : require('@/assets/favorites.png')" />
                      </el-tooltip>

                      <div class="b-card-top__top-menu"
                           v-if="currentPermission['moreMenuAuth']">
                        <BMoreMenu :options="dropdownMenus"
                                   :permission="{
                                    delete:deleteButtonAuth && deleteButtonAuth(item),
                                    clone:cloneButtonAuth && cloneButtonAuth(item),
                                    share:shareButtonAuth && shareButtonAuth(item),
                                    edit:editButtonAuth && editButtonAuth(item),
                                  }"
                                   @command="(command) => onCommand(command,item)" />
                      </div>
                    </div>

                    <div class="b-card-top__center flex items-center">
                      <div class="b-card-top__center-desc flex-1">
                        <ZTooltip :line="1"
                                  :content="item.description">
                          <span>{{item.description}}</span>
                        </ZTooltip>
                      </div>
                    </div>

                    <div class="b-card-top__bottom flex items-center">

                      <ZTag :type="useBusinessType(item.businessType)">
                        {{item.businessTypeName}}
                      </ZTag>

                      <BIntegration class="b-card-top__bottom-integration"
                                    :options="item.integrationList || []"
                                    :prop="{name:'name'}" />
                    </div>
                  </div>

                  <div class="b-card-bottom flex justify-between"
                       v-if="currentPermission['cardFooterAuth']">
                    <div>
                      <BCardInfoItem :title="$t('custom.component.viewComponent.created')"
                                     :date="timeFormat(item.createTime,'HH:mm:ss')"
                                     :name="item.creatorName" />
                      <BCardInfoItem :title="$t('custom.component.viewComponent.update')"
                                     :date="timeFormat(item.updateTime,'HH:mm:ss')"
                                     :name="item.updateByName" />
                      <BCardInfoItem :maxWidth="200" :title="$t('custom.component.viewComponent.read')">
                        <template v-slot:date>
                          <div class="re-tontent flex items-center">
                            <span :class="item.ready > 0 ? 'heightline':''"
                                  @click.stop="onSelectNum('ready',item)">{{item.ready}}</span>
                            <span>/</span>
                            <span :class="item.received > 0 ? 'heightline':''"
                                  @click.stop="onSelectNum('received',item)">{{item.received}}</span>
                            <span>/</span>
                            <span :class="item.read > 0 ? 'heightline':''"
                                  @click.stop="onSelectNum('read',item)">{{item.read}}</span>
                            <span>/</span>
                            <span :class="item.emailSent > 0 ? 'heightline':''"
                                  @click.stop="onSelectNum('read',item)">{{item.emailSent || 0}}</span>
                          </div>
                        </template>
                      </BCardInfoItem>
                    </div>

                    <div class="flex"
                         v-if="item.businessType !== 'Template'"
                         @click.stop>
                      <BSwitchMessage :value="item.enable"
                                      style="margin-left:20px"
                                      @change="(val)=>toggleSwitch(item,val,'enable')"
                                      :disabled="!$hasPermission('sys:bots:switch')"
                                      :name="$t('custom.component.viewComponent.trigger')"
                                      :tooltipText="$t('custom.botStore.triggerTootips')" />
                      <BSwitchMessage :value="item.alert"
                                      style="margin-left:20px"
                                      @change="(val)=>toggleSwitch(item,val,'alert')"
                                      :name="$t('custom.component.viewComponent.alert')"
                                      :disabled="!item.enable||!$hasPermission('sys:bots:switch')"
                                      :tooltipText="$t('custom.botStore.alertTootips')" />
                      <BSwitchMessage :value="item.escalation"
                                      style="margin-left:20px"
                                      @change="(val)=>toggleSwitch(item,val,'escalation')"
                                      :name="$t('custom.component.viewComponent.escalate')"
                                      :disabled="item.enable===false || item.alert===false||!$hasPermission('sys:bots:switch')"
                                      :tooltipText="$t('custom.botStore.escalateTootips')" />
                    </div>
                  </div>

                  <BlockLoading v-show="item._loading" />
                </div>
              </template>
            </RecycleScroller>

            <slot v-else
                  name="empty"
                  v-bind="{
                  selectedFast
                }"></slot>
          </div>

          <div :class="[
          'bot-list__wrapper-right-footer flex items-center justify-between',
          {
            'flex-row-reverse':paginationPosition === 'left'
          }
        ]"
               v-if="currentPermission['footerAuth']">

            <slot name="footer-action"
                  v-if="$slots['footer-action'] && currentPermission['footerActionAuth']"></slot>

            <slot name="footer-pagination"
                  v-if="currentPermission['paginationAuth']">
              <el-pagination :current-page="searchForm.pagination.currentPage"
                             :page-sizes="searchForm.pagination.pageSizes"
                             :pagerCount="searchForm.pagination.pageCount"
                             :page-size="searchForm.pagination.pageSize"
                             layout="total, sizes, prev, pager, next, jumper"
                             :total="searchForm.pagination.total"
                             @size-change="sizeChangeResource"
                             @current-change="currentChangeResource">
              </el-pagination>
            </slot>
          </div>
        </div>

      </div>
    </div>
  </ZContainer>
</template>

<script>
import ZContainer from '@/components/storybook/z-container'
import BFastMenu from '@/components/storybook/b-fast/b-fast-menu'
import BSort from '@/components/storybook/b-sort/index'
import BFilter from '@/components/storybook/b-filter/index'
import BIntegrationGroup from '@/components/storybook/b-integration-group/index'
import BFast from '@/components/storybook/b-fast/index'
import { merge, pick, keys, delay, isFunction, debounce, values, get } from 'lodash'
import permissionProps from '../permission.prop'
import { parseFast, parseSearch } from '@/components/storybook/hooks/useFast'
import useErrorMessage from '@/components/storybook/hooks/useErrorMessage'
import ZTooltip from '@/components/storybook/z-tooltip'
import BlockLoading from '@/components/storybook/z-loading'
import BCardInfoItem from '@/components/storybook/b-card/info-item'
import BIntegration from '@/components/storybook/b-integration/index'
import BMoreMenu from '@/components/storybook/b-card/more-menu'
import TagGroup from '@/components/tag-group'
import bus from '@/components/storybook/utilties/bus'
import useGadget from '@/components/storybook/hooks/useGadget'
import useStatusColor from '@/components/storybook/hooks/useStatusColor'
import useBusinessType from '@/components/storybook/hooks/useBusinessType'
import { timeFormat } from '@/components/storybook/utilties/tools'
import ZTag from '@/components/storybook/z-tag'
import BSwitchMessage from '@/components/storybook/b-switch-message/index.vue'
import BBlockStatus from '@/components/storybook/b-block-status/index.vue'
import { fetchBotFilter, deleteFilter, fetchTag, fetchWorkScheduledUser, fetchIntegration, fetchBotList, createFavorite, deleteFavorite } from '@/api/new'

const EVENTS = {
  useGadget,
  useStatusColor,
  useBusinessType,
  timeFormat
}

export default {
  inject:{isDefaultRole: {default:false}},
  name: 'BotList',
  components: {
    ZContainer,
    BFastMenu,
    BSort,
    BFilter,
    BFast,
    BIntegrationGroup,
    ZTooltip,
    BCardInfoItem,
    BIntegration,
    BMoreMenu,
    TagGroup,
    ZTag,
    BSwitchMessage,
    BlockLoading,
    BBlockStatus
  },
  props: {

    collapse: Boolean,
    // 0:selection 1:variable
    model: {
      type: String,
      default: 'variable'
    },
    filterProps: {
      type: Object,
      default: () => ({})
    },
    paginationPosition: {
      type: String,
      default: 'left'
    },

    // table query parameter
    searchForm: {
      type: Object,
      default: () => ({})
    },

    // fast query parameter
    fastForm: {
      type: Object,
      default: () => ({})
    },
    // activate fast immediately
    immediateFast: {
      type: Boolean,
      default: true
    },
    // fast's props
    fastProps: {
      type: Object,
      default: () => ({})
    },

    // format row
    formatRow: Function,

    // format selection bot data
    formatSelection: Function,
    // selected bot
    selectionRows: {
      type: Array,
      default: () => ([])
    },
    disabledRowFormat: Function,
    // key of line bot data
    rowKey: {
      type: String,
      default: 'id'
    },

    // permissions of the operation button
    cloneButtonAuth: Function,
    shareButtonAuth: Function,
    editButtonAuth: Function,
    deleteButtonAuth: Function,

    // permissions
    permission: Object,
    ...permissionProps

  },
  data () {
    return {
      // loading status
      fastLoading: false,
      collectLoading: false,
      resourceLoading: false,
      loading: false,

      // fast
      fastGuideTooltipVisible: false,
      fasts: [],
      selectedFast: {},

      // collapse status
      sourceCollapse: this.collapse,
      sortCollapse: true,
      filterCollapse: true,

      sortFields: Object.freeze([
        {
          value: 'name',
          label: 'Name'
        },
        {
          value: 'business_type',
          label: 'Type'
        },
        {
          value: 'status',
          label: 'Status'
        },
        {
          value: 'create_date',
          label: 'Created Date'
        },
        {
          value: 'creatorName',
          label: 'Creator'
        },
        {
          value: 'update_date',
          label: 'Last Modified'
        },
        {
          value: 'updateByName',
          label: 'Updater'
        },
        {
          value: 'ready',
          label: 'Ready'
        },
        {
          value: 'received',
          label: 'Received'
        },
        {
          value: 'read',
          label: 'Read'
        }
      ]),

      // filter select
      users: [],
      tags: [],
      statusOptions: [],
      integrations: [],
      businessTypes: [],

      resources: [],
      dropdownMenus: Object.freeze([
        {
          command: 'edit',
          icon: 'cuifont icon_edit',
          name: this.$t('custom.component.viewComponent.edit')

        },
        {
          command: 'clone',
          icon: 'cuifont icon_copy1',
          name: this.$t('custom.component.viewComponent.clone')

        },
        {
          command: 'share',
          icon: 'cuifont icon_share',
          name: this.$t('custom.component.viewComponent.share')

        },
        {
          command: 'delete',
          icon: 'cuifont icon_delete',
          name: this.$t('custom.component.viewComponent.delete')
        }
      ]),
      ...EVENTS,
      selectionRowsClone: [],
    }
  },
  computed: {
    currentCollapse: {
      get () {
        return !!this.sourceCollapse
      },
      set (collapse) {
        this.sourceCollapse = collapse
        this.$emit('update:collapse', collapse)
      }
    },
    currentPermission () {
      return merge(pick(this.$props, keys(permissionProps)), this.permission)
    },
    currentFilterProps () {
      return merge(this.filterProps, {
        users: this.users,
        tags: this.tags,
        status: this.statusOptions,
        businessTypes: this.businessTypes
      })
    }
  },
  watch: {
    filterCollapse (collapse) {
      if (!collapse) {
        this.sortCollapse = true
      }
    },
    sortCollapse (collapse) {
      if (!collapse) {
        this.filterCollapse = true
      }
    }
  },
  created () {
    this.selectionRowsClone = this.selectionRows
    this.init()
    bus.$on('event:deleteList', (item) => {
      this.onSelectResource(item)
    })
    bus.$on('update:tags', (data) => {
      if (data && data.length>0) { 
        this.tags = data || []
      }
    })
  },
  beforeDestroy () {
    bus.$off('event:deleteList')
    bus.$off('update:tags')
  },
  methods: {
    toggleSwitch (item, value, type) {
      bus.$emit('event:change-switch', { item, value, type })
      this.$emit('event:change-switch', { item, value, type })
    },
    async getBusinessTypes () {
      const value = window.SITE_CONFIG['dictList'].find(e => e.dictType === 'datasets_type_list')
      if (value) {
        const list = value.dataList || []
        if (this.searchForm.resourceType === 130 || this.searchForm.resourceType === 110) {
          return list.filter(item => item.dictValue === 'MSPbots Internal')
        }

        return list.filter(item => item.dictValue !== 'MSPbots Internal'
        )
      }
      return []
    },
    backDefaultSort () {
      this.searchForm.order = [{ field: 'update_date', sort: 'DESC' }]
      this.refreshTable()
    },
    keyWordsChange: debounce(function () {
      this.resourceLoading = true
      this.searchForm.pagination.currentPage = 1
      return this.getTableData().then(resources => {
        this.resources = resources.records.map(i=>{
          return {
            ...i,
            resourceName: i.name,
            resourceId: i.id
          }
        }) || []
        this.searchForm.pagination.total = resources.total || 0
      }).finally(() => {
        this.resourceLoading = false
      })
    }, 1000),
    onSelectNum (type, item) {
      this.$emit(`event:select-${type}`, item)
      bus.$emit(`event:select-${type}`, item)
    },
    onCommand (command, item, index) {
      if (command === 'select' && !this.isDisabledRow(item)) {
        this.onSelectResource(item, index)
      }
      if (command === 'edit') {
        this.onEditResource(item, index)
      }
      if (command === 'collect') {
        this.onCollectResource(item, index)
      }
      if (command === 'clone') {
        this.onCloneResource(item, index)
      }
      if (command === 'delete') {
        this.onDeleteResource(item, index)
      }
      if (command === 'share') {
        this.onShareResource(item, index)
      }
      if (command === 'draw') {
        this.onDrawResource(item, index)
      }
    },

    isSelectedRow (item) {
      return this.selectionRowsClone.some(record => record.resourceId === item[this.rowKey])
    },
    isDisabledRow (item) {
      return isFunction(this.disabledRowFormat) ? this.disabledRowFormat(item) : false
    },
    onSelectResource (item) {
      const row = isFunction(this.formatSelection) ? this.formatSelection(item) : item
      const index = this.selectionRowsClone.findIndex(record => record.resourceId === row[this.rowKey])
      if (index !== -1) {
        this.selectionRowsClone.splice(index, 1)
        return
      }
      this.selectionRowsClone.unshift(row)
      this.$emit('event:select', row)
      bus.$emit('event:select', row)
    },
    onEditResource (item) {
      this.$emit('event:edit', item)
      bus.$emit('event:edit', item)
    },
    async onCollectResource (item) {
      if (this.collectLoading) {
        return
      }
      try {
        this.collectLoading = true
        if (item.isFavorite) {
          await this.onRemoveFavorite(item)
        } else {
          await this.onSaveFavorite(item)
        }

        this.$emit('event:collect', item)
        bus.$emit('event:collect', item)

        if (!item.isFavorite) {
          this.refreshTable()
        }
        this.refreshFast()
      } catch (error) {
        this.$message.error(error)
      } finally {
        this.collectLoading = false
      }
    },
    onCloneResource (item) {
      this.$emit('event:clone', item)
      bus.$emit('event:clone', item)
    },
    onDeleteResource (item) {
      this.$emit('event:delete', item)
      bus.$emit('event:delete', item)
    },
    onShareResource (item) {
      this.$emit('event:share', item)
      bus.$emit('event:share', item)
    },
    onDrawResource (item) {
      this.$emit('event:draw', item)
      bus.$emit('event:draw', item)
    },
    async onSaveFavorite (item) {
      const { id } = item
      const { resourceType } = this.searchForm
      const params = {
        userId: this.$store.state.user.id,
        resourceId: id,
        resourceType,
        creator: this.$store.state.user.id
      }
      const { data: response } = await createFavorite(params)
      if (response.code !== 0) {
        throw response.msg
      }

      this.$set(item, 'isFavorite', true)
    },
    async onRemoveFavorite (item) {
      const { id } = item
      const { resourceType } = this.searchForm
      const params = {
        id,
        resourceType
      }
      const { data: response } = await deleteFavorite(params)
      if (response.code !== 0) {
        throw response.msg
      }

      this.$set(item, 'isFavorite', false)
    },
    async sizeChangeResource (size) {
      try {
        this.resourceLoading = true
        this.searchForm.pagination.currentPage = 1
        this.searchForm.pagination.pageSize = size
        const resources = await this.getTableData()
        this.resources = resources.records.map(i=>{
          return {
            ...i,
            resourceName: i.name,
            resourceId: i.id
          }
        }) || []
        this.searchForm.pagination.total = resources.total || 0
      } catch (error) {
      } finally {
        this.resourceLoading = false
      }
    },
    async currentChangeResource (current) {
      try {
        this.resourceLoading = true
        this.searchForm.pagination.currentPage = current
        const resources = await this.getTableData()
        this.resources = resources.records.map(i=>{
          return {
            ...i,
            resourceName: i.name,
            resourceId: i.id
          }
        }) || []
        this.searchForm.pagination.total = resources.total || 0
      } catch (error) {
      } finally {
        this.resourceLoading = false
      }
    },

    openFastModal () {
      this.$emit('event:open-fast-modal')
    },
    async openFastGuide () {
      const customFast = this.fasts.find(i => i.id)
      this.currentCollapse = false
      if (!customFast) {
        this.filterCollapse = false
        this.fastGuideTooltipVisible = true
        // eslint-disable-next-line no-return-assign
        delay(() => this.fastGuideTooltipVisible = false, 1500)
      }
    },
    async onDeleteFast (fast) {
      try {
        await this.$confirm(this.$t('prompt.info', { 'handle': this.$t('delete') }), this.$t('prompt.title'), {
          confirmButtonText: this.$t('confirm'),
          cancelButtonText: this.$t('cancel'),
          type: 'warning'
        })
        this.fastLoading = true
        const { id } = fast

        const { data: response } = await deleteFilter(id)
        if (response.code !== 0) {
          throw response.msg
        }
        this.fasts = await this.getFasts()
        const findFast = this.fasts.find(i => i.total)

        if (findFast) {
          Object.assign(this.searchForm, parseFast(findFast.filterJson, 'bot'))
          this.selectedFast = findFast
          this.refreshTable()
        }
      } catch (error) {
        useErrorMessage(error)
      } finally {
        this.fastLoading = false
      }
    },
    async onSelectFast ({ name }) {
      try {
        this.resourceLoading = true
        const fast = this.fasts.find(i => i.name === name)
        if (fast) {
          Object.assign(this.searchForm, parseFast(fast.filterJson, 'bot'))
          this.searchForm.pagination.currentPage = 1
          const resources = await this.getTableData()
          this.resources = resources.records.map(i=>{
          return {
            ...i,
            resourceName: i.name,
            resourceId: i.id
          }
        }) || []
          this.searchForm.pagination.total = resources.total || 0
        }
      } catch (error) {
      } finally {
        this.resourceLoading = false
      }
    },
    async refreshTable (refresh) {
      try {
        this.resourceLoading = true
        this.searchForm.pagination.currentPage = 1
        const resources = await this.getTableData(refresh)
        this.resources = resources.records.map(i=>{
          return {
            ...i,
            resourceName: i.name,
            resourceId: i.id
          }
        }) || []
        this.searchForm.pagination.total = resources.total || 0
      } catch (error) {

      } finally {
        this.resourceLoading = false
      }
    },
    async refreshFast (refresh) {
      try {
        this.fastLoading = true
        this.fasts = await this.getFasts(refresh)
      } catch (error) {

      } finally {
        this.fastLoading = false
      }
    },

    async init () {
      try {
        this.loading = true
        const fasts = await this.getFasts()
        const fast = (this.isDefaultRole&&this.isDefaultRole())? fasts.find(i => i.name === 'Template Bots'): fasts.find(i => i.total)
        if (fast && this.immediateFast) {
          Object.assign(this.searchForm, parseFast(fast.filterJson, 'bot'))
          this.selectedFast = fast
        }
        const [
          resources,
          users,
          tags,
          integrations,
          statusOptions,
          businessTypes
        ] = await Promise.all([
          this.getTableData(),
          this.getUsers(),
          this.getTags(),
          this.getIntegrations(),
          this.getStatusOptions(),
          this.getBusinessTypes()
        ])
        this.resources = resources.records.map(i=>{
          return {
            ...i,
            resourceName: i.name,
            resourceId: i.id
          }
        }) || []
        this.searchForm.pagination.total = resources.total || 0
        this.tags = tags
        this.users = users.sort((a, b) => a.username.localeCompare(b.username))
        this.integrations = values(integrations).sort((a, b) => (get(a, 'name') || '').charCodeAt(0) - (get(b, 'name') || '').charCodeAt(0))
        this.statusOptions = statusOptions
        this.fasts = fasts
        this.businessTypes = businessTypes
      } catch (error) {
      } finally {
        this.loading = false
        this.$store.state.REFRESHCACHE = false
      }
    },
    async getFasts (refresh) {
      const { businessType, type } = this.fastForm
      const params = {
        businessType,
        type,
        queryType: refresh || this.$store.state.REFRESHCACHE ? 'REFRESHCACHE' : null,
      }
      const { data: response } = await fetchBotFilter(params)
      if (response.code !== 0) {
        throw response.msg
      }
      return response.data || []
    },
    async getTableData (refresh) {
      const params = {
        ...parseSearch(this.searchForm, 'bot'),
        queryType: refresh || this.$store.state.REFRESHCACHE ? 'REFRESHCACHE' : null,
      }
      const { data: response } = await fetchBotList(params)
      if (response.code !== 0) {
        throw response.msg
      }
      const { records = [], ...rest } = response.data || {}
      if (isFunction(this.formatRow)) {
        return {
          ...rest,
          records: records.map(item => this.formatRow(item))
        }
      }
      return response.data || {}
    },
    async getTags () {
      const params = {}

      const { data: response } = await fetchTag(params)

      if (response.code !== 0) {
        throw response.msg
      }

      return response.data || []
    },
    async getUsers () {
      const params = {
        status: 1,
        excludeRegSource: '3'
      }
      const { data: response } = await fetchWorkScheduledUser(params)
      if (response.code !== 0) {
        throw response.msg
      }

      return response.data || []
    },
    async getIntegrations () {
      const params = {
        tenantCode: this.$store.state.user.tenantCode,
        loadType: 3
      }
      const { data: response } = await fetchIntegration(params)
      if (response.code !== 0) {
        throw response.msg
      }
      return response.data || {}
    },
    async getStatusOptions () {
      let options = []
      if (this.$hasPermission(`sys:bot:status:alpha`)) {
        options.push({ dictLabel: 'Alpha', dictValue: 'Alpha' })
      }
      if (this.$hasPermission(`sys:bot:status:requested`)) {
        options.push({ dictLabel: 'Requested', dictValue: 'Requested' })
      }
      if (this.$hasPermission(`sys:bot:status:in-dev`)) {
        options.push({ dictLabel: 'In-Dev', dictValue: 'In-Dev' })
      }
      if (this.$hasPermission(`sys:bot:status:published`)) {
        options.push({ dictLabel: 'Published', dictValue: 'Published' })
      }
      if (this.$hasPermission(`sys:bot:status:in-qa`)) {
        options.push({ dictLabel: 'In-QA', dictValue: 'In-QA' })
      }
      return options
    }

  }
}
</script>

<style lang="scss" scoped>
@import "@/components/storybook/b-card/b-card.scss";
.bot-list {
  &__wrapper {
    &-left {
      width: 283px;
      transition: all 200ms;
      transition: all 200ms;
      padding: 16px 0px;
      box-shadow: 1px 0px 0px 0px #f0f0f0;
    }
    &-right {
      transition: all 200ms;
      padding-bottom: 16px;
      &-action {
        padding: 16px 16px 0 16px;
      }
      &-list {
        padding: 16px 16px 0;
      }
      &-footer {
        padding: 16px 16px 0;
        & > .el-pagination {
          margin-top: 0;
          padding: 2px 0px;
        }
      }
    }
  }

  &--collapse {
    .bot-list__wrapper-left {
      width: 0;
    }
  }
}

.bot-switch {
  margin-left: 20px;
  &-name {
    color: #7f7f7f;
    padding-bottom: 5px;
  }
}

.re-tontent {
  span {
    padding-right: 10px;
  }
  .heightline {
    color: $--theme-color;
  }
}
</style>
